/*
 * IpMaskChecker.cpp
 *
 *  Created on: 13.11.2011
 *      Author: Pavel Sinay
 */

#include "IpMaskChecker.h"
#include <vector>
#include <iostream>
#include <stdlib.h>

IpMaskChecker::IpMaskChecker() {
}

IpMaskChecker::~IpMaskChecker() {
}

Result IpMaskChecker::parse_ip(std::string ip_str, uint32_t & ip) {
	std::vector<std::string> substrings;
	int dot_position = 0;
	while ((dot_position = ip_str.find('.')) > 0) {
		std::string substr;
		substr.assign(ip_str.begin(), ip_str.begin() + dot_position);
		ip_str.erase(0, dot_position + 1);
		substrings.push_back(substr);
	}
	substrings.push_back(ip_str);

	if (substrings.size() != 4) {
		return result_error;
	}

	ip = 0;
	uint32_t fragment;
	for (int i = 0; i != substrings.size(); ++i) {
		fragment = atoi(substrings[i].c_str());
		ip += fragment << (3 - i) * 8;
	}

	//std::cout << "IP = " << ip << std::endl;
	return result_yes;
}

Result IpMaskChecker::check(const std::string & mask, const std::string & ip1,
		const std::string & ip2) {
	uint32_t mask_int, ip1_int, ip2_int;
	if (parse_ip(mask, mask_int) == result_error || parse_ip(ip1, ip1_int)
			== result_error || parse_ip(ip2, ip2_int) == result_error) {
		return result_error;
	}

	if ((ip1_int & mask_int) == (ip2_int & mask_int)) {
		return result_yes;
	} else {
		return result_no;
	}
}

